package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import utils.Log4Test;

/**
 * Created by Mikhail.Chub on 29/05/2014.
 */
public class HomePage extends BasePage{

    private String url = "http://rozetka.com.ua/";
    protected static final String PRODUCT_FOUND_LOCATOR = "//a[contains(text(),'%s')]";
    protected static final By SEARCH_BTN_LOCATOR = By.className("btn-link-i");
    protected static final By SEARCH_FIELD_LOCATOR = By.name("text");
    protected static final By COMPARE_PRODUCT_LOCATOR = By.name("tocomparison");
    public static final By ALREADY_IN_COMPARISON_LOCATOR = By.name("comparison_catalog");
    public static final By COMPARISON_LOCATOR = By.xpath("//div[@name='comparison_catalog']/a");

    public HomePage (PageManager pageManager) {
        super(pageManager);
    }

    public void open() {
        driver.get(url);
    }

    public boolean isOpened() {
        String currentUrl = driver.getCurrentUrl();
        boolean opened = currentUrl.equals(url);
        if (opened) {Log4Test.info("Home page: '" + currentUrl + "' is opened");}
        else {Log4Test.error("Home page: '" + url + "' is not opened! '" + currentUrl + "' is opened instead");}
        return opened;
    }

    public void fillSearchField(String searchString) {
        fillTxtField(SEARCH_FIELD_LOCATOR, searchString);
    }

    public void initiateSearch() {
        click(SEARCH_BTN_LOCATOR);
    }

    public boolean isProductFound(String productName) {
        boolean found = driver.findElement(By.xpath(String.format(PRODUCT_FOUND_LOCATOR, productName))).isDisplayed();
        if (found) {Log4Test.info("Product '" + productName + "' is found");}
        else {Log4Test.error("Product '" + productName + "' is not found!");}
        return found;
    }

    public void addProductToComparison() {
        WebDriverWait wait = new WebDriverWait(driver,20);
        wait.until(ExpectedConditions.visibilityOfElementLocated(COMPARE_PRODUCT_LOCATOR));
        wait.until(ExpectedConditions.elementToBeClickable(COMPARE_PRODUCT_LOCATOR));
        click(COMPARE_PRODUCT_LOCATOR);
    }

    public void gotoComparison() {
        WebDriverWait wait = new WebDriverWait(driver,20);
        wait.until(ExpectedConditions.visibilityOfElementLocated(COMPARISON_LOCATOR));
        wait.until(ExpectedConditions.elementToBeClickable(COMPARISON_LOCATOR));
        click(COMPARISON_LOCATOR);
    }


}
